<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/24 0024
 * Time: 10:16
 */
$level = 0;
$char_data = '';
$xml = xml_parser_create('UTF-8');

xml_set_element_handler($xml, 'start_handler', 'end_handler');
xml_set_character_data_handler($xml, 'character_handler');
//xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, false);


$res = xml_parse($xml, file_get_contents('./test.xml'));

function flush_data()
{
    global $level, $char_data;
    /**
     * 当存在数据是 修正数据 并且输出
     */
    $char_data = trim($char_data);
    if (strlen($char_data) > 0) {
        echo PHP_EOL;
        //精心封装它 使它适合一个终端的屏幕
        $data = explode("\n", wordwrap($char_data, 76 - ($level * 2)));
        foreach ($data as $line) {
            echo str_repeat(' ', ($level + 1)) . "[" . $line . "]\n";
        }
    }
    /**
     * 清除缓冲区的数据
     */
    $char_data = '';
}

function start_handler($xml, $stag, $attributes)
{
    //echo '触发了吗';
    global $level;
    /**
     * 从字符串处理器中清空收集的数据
     */
    flush_data();
    /**
     * 把属性变为一个字符串 然后输出
     */
    echo "\n" . str_repeat(' ', $level) . "$stag";

    foreach ($attributes as $index => $attribute) {
        echo "$index = $attribute";
    }
    //提高缩进级别
    $level++;
}

function end_handler($xml, $stag)
{
    //echo '触发了吗';
    global $level;
    /**
     * 从字符串处理器中清空收集的数据
     */
    flush_data();
    /**
     * 减少缩进的尺度 并且打印结束标记
     */
    $level--;
    echo PHP_EOL . str_repeat(' ', $level) . "/$stag";
}

function character_handler($xml, $data)
{
//    echo '触发了吗';
    /**
     * 正佳字符处理器到缓冲区中
     */
    global $level, $char_data;
    $char_data .= ' ' . $data;
}


